const app = getApp()
import api from '../../utils/api'
// pages/order/order.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canteenOrderId: '',
    menu_date: '',
    isAblemodify: false,  // 是否可修改  初始为false
    modifyStatus: false,  // 是否处于修改状态
    deadline: '', // 订餐截止时间
    originalOrderList: [], // 原始list，用于取消修改恢复初始数据
    orderList: [],
    foodType: [],
    foodTotalAmount: 0,
    // 半屏dialog
    dialogFlag: false,
    otherFoodList: [],
    currentMeal: 0,
    // 自定义dialog
    cuatomDialogFlag: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let orderList = JSON.parse(wx.getStorageSync('orderList'))
    let foodTotalAmount = 0
    let foodType = []
    orderList.forEach((item, index) => {
      let obj = {
        meal: item[0] && item[0].meal,
        name: item[0] && item[0].meal == 0 ? '早餐' : '午餐',
        count: 0
      }
      foodType.push(obj)
      item.forEach((jtem, jndex) => {
        jtem.count = jtem.label
        foodTotalAmount += jtem.count ? jtem.count * jtem.price : 0
        foodType[index].count += jtem.count ? jtem.count * 1 : 0
      })
    })
    this.setData({
      canteenOrderId: options.id,
      menu_date: options.menu_date,
      isAblemodify: options.isAble == 'true' ? true : false,
      deadline: options.deadline,
      originalOrderList: JSON.parse(JSON.stringify(orderList)),
      orderList: orderList,
      foodType: foodType,
      foodTotalAmount: foodTotalAmount
    })
  },
  // 加减餐品
  handleCount: function (e) {
    let orderList = this.data.orderList
    let foodType = this.data.foodType
    let foodTotalAmount = this.data.foodTotalAmount
    let action = e.currentTarget.dataset.action, index = e.currentTarget.dataset.index, meal = e.currentTarget.dataset.meal;
    if (action == 'add') {
      orderList[meal][index].count ++
      foodType[meal].count ++
      foodTotalAmount += orderList[meal][index].price
    } else if (action == 'minus') {
      orderList[meal][index].count --
      foodType[meal].count --
      foodTotalAmount -= orderList[meal][index].price
    }
    this.setData({
      orderList: orderList,
      foodType: foodType,
      foodTotalAmount: foodTotalAmount
    })
    // if (this.data.foodTotalCount <= 0) {
    //   this.setData({
    //     dialogFlag: false
    //   })
    // }
  },
  handleCount1: function (e) {
    let otherFoodList = this.data.otherFoodList
    let action = e.currentTarget.dataset.action, index = e.currentTarget.dataset.index, meal = e.currentTarget.dataset.meal;
    if (action == 'add') {
      otherFoodList[index].count ++
    } else if (action == 'minus') {
      otherFoodList[index].count --
    }
    this.setData({
      otherFoodList: otherFoodList
    })
  },
  // 选择其他套餐
  selectOtherFood: function (e) {
    let otherFoodList = JSON.parse(JSON.stringify(this.data.orderList))[e.currentTarget.dataset.meal] // 解决地址引用会出现跟随改变情况
    this.setData({
      dialogFlag: true,
      otherFoodList: otherFoodList,
      currentMeal: e.currentTarget.dataset.meal
    })
  },
  isDialogShow: function (e) {
    if (e.currentTarget.dataset.show == 'true') {
      let orderList = this.data.orderList
      orderList[this.data.currentMeal] = this.data.otherFoodList
      let foodType = this.data.foodType
      let foodTotalAmount = 0
      orderList.forEach((item, index) => {
        foodType[index].count = 0
        item.forEach(jtem => {
          foodTotalAmount += jtem.price * jtem.count
          foodType[index].count += jtem.count
        })
      })
      this.setData({
        orderList: orderList,
        foodType: foodType,
        foodTotalAmount: foodTotalAmount
      })
    }
    this.setData({
      dialogFlag: false
    })
  },
  // 提交修改订单
  submitOrder: function () {
    // 如果数量均为0，直接调取消订单的接口
    let totalCount = 0
    let foodType = this.data.foodType
    foodType.forEach(item => {
      totalCount += item.count
    })
    if (totalCount <= 0) {
      this.setData({
        customDialogFlag: true
      })
    } else {
      let indent = '', count = '', _this= this;
      this.data.orderList.forEach(item => {
        item.forEach(jtem => {
          if (jtem.count > 0) {
            indent += '/' + jtem.dish_id
            count += '/' + jtem.count
          }
        })
      })
      wx.request({
        url: api.orderFood,
        method: "POST",
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        data: {
          'id': this.data.canteenOrderId,
          'menu_date': this.data.menu_date,
          'canteen_id': 3,  // 目前只有3，实际应从上一个页面传入
          'indent': indent.slice(1),
          'count': count.slice(1)
        },
        success(res) {
          if (res.data.state == 1) {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
            })
            // 直接返回上层最简单
            setTimeout(() => {
              _this.goBack()
            }, 2000)
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'error',
            })
          }
        }
      })
    }
  },
  // 取消订单前弹窗确认
  cancelOrder: function () {
    this.setData({
      customDialogFlag: true
    })
  },
  // 修改订单
  modifyOrder: function (e) {
    if (e.currentTarget.dataset.show == 'false') {
      this.setData({
        orderList: JSON.parse(JSON.stringify(this.data.originalOrderList)),
        modifyStatus: false
      })
    } else {
      this.setData({
        modifyStatus: true
      })
    }
  },
  // 自定义dialog，取消订单操作
  isCustomDialogShow: function (e) {
    if (e.currentTarget.dataset.show == 'true') {
      // 取消订单
      let _this = this
      wx.request({
        url: api.cancel + "?id=" + this.data.canteenOrderId,
        method: "GET",
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success(res) {
          if (res.data.state == 1) {
            wx.showToast({
              title: '取消成功',
              icon: 'success',
            })
            // 直接返回上层最简单
            setTimeout(() => {
              _this.goBack()
            }, 2000)
          }
        }
      })
    }
    this.setData({
      customDialogFlag: false
    })
  },
  // 返回上一层
  goBack: function (e) {
    // 小程序自带返回不影响
    let pages = getCurrentPages();
    let prvePage = pages[pages.length - 2]
    prvePage.setData({
      fromOrder: true
    })
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})